import React, { useState, useRef } from 'react';
import { Breadcrumb, Button, Card, Input, Radio, Table, Image, Modal, Form, notification, Upload, InputNumber, DatePicker } from 'antd';
import { RedoOutlined, MoreOutlined, DeleteOutlined, AudioOutlined, PlusOutlined, PlusCircleOutlined } from '@ant-design/icons';
import '../../style/tripmanage.scss'
import axios from 'axios';
import { useEffect } from 'react';
import { useTripmanage } from '../../hooks/tripmanage'
import { useForm } from 'antd/es/form/Form';
import { useNavigate } from 'react-router-dom';
import { del_list, search_list, tripmanage_list, search_list2 } from '../../utils/api2'

//表单组件

//表格组件
const suffix = (
  <AudioOutlined
    style={{
      fontSize: 16,
      color: '#1890ff',
    }}
  />
);

function Tripmanage(props) {
  //调用钩子函数获取表格数据
  var [list, setList] = useTripmanage()
  //在初始挂载期发送分页请求
  useEffect(() => {
    tripmanage_list().then((res) => {
      console.log(res.data);
      setList(res.data)
      setpaination({ current: pagination.current, pageSize: 5, total: res.data.length })
    })
  }, [])
  //图片上传
  const [fileList, setFileList] = useState([]);
  const onChange = ({ fileList: newFileList }) => {
    setFileList(newFileList);


  };
  const onPreview = async (file) => {
    let src = file.url;
    if (!src) {
      src = await new Promise((resolve) => {
        const reader = new FileReader();
        reader.readAsDataURL(file.originFileObj);
        reader.onload = () => resolve(reader.result);
      });
    }
    const image = new Image();
    image.src = src;
    const imgWindow = window.open(src);
    imgWindow?.document.write(image.outerHTML);
  };
  const columns = [
    {
      title: '学号',
      dataIndex: 'con',
    },
    {
      title: '姓名',
      dataIndex: 'name',
      render: (text) => <a>{text}</a>,
    },
    {
      title: '行程',
      dataIndex: 'itinerary',
    },
    {
      title: '日期',
      dataIndex: 'Ctime',
    },
    {
      title: '行程码',
      render: (key, record) => (
        <>
          <div className='Up'>
            <Upload
              action={localStorage.setItem('pic', JSON.stringify(fileList))}
              listType="picture-card"
              accept='.png,.jpg,.gif,.jepg'
              fileList={record.fileList}
              onChange={onChange}
              onPreview={onPreview}
            >
              {fileList.length <= 1 && '上传行程码'}
            </Upload>
          </div>

          {/* <Image
                  className='Zhan'
                  width={50}
                  height={50}
                  src="error"
                  fallback=""
              /> */}

        </>
      )

    },
    {
      title: '健康码',
      render: (record) => (
        <>
          <div className='Up'>
            <Upload
              action=''
              listType="picture-card"
              accept='.png,.jpg,.gif,.jepg'
              fileList={record.fileList}
              onChange={onChange}
              onPreview={onPreview}
            >
              {fileList.length <= 1 && '上传健康码'}
            </Upload>
          </div>
        </>
      )

    },
    {
      title: '添加时间',
      dataIndex: 'Utime',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record, key) => (
        <>
          <MoreOutlined className='edit' onClick={() => { More(record) }} />
          <DeleteOutlined className='del' onClick={() => { del(record) }} />
        </>
      )
    }

  ];

  const config = {
    rules: [
      {
        type: 'object',
        required: true,
        message: '请输入日期',
      },
    ],
  };
  // 更多操作按钮
  var [params, setParams] = useState({})
  var More = (record) => {
    console.log(record);
    setParams(record)
    setIsModalOpen(true)
      
  }
  //表单提交按钮
  // 创建form实例
  const [form] = Form.useForm()
  // const [value,setvalue] = useState({})
  const onFinish = (values) => {
    console.log(values);
    axios.patch(`/trip/${params.id}`, { name: values.name, con: values.con, itinerary: values.itinerary, Ctime: time.$y + '-' + (time.$M + 1) + '-' + time.$D, Utime: time2.$y + '-' + (time2.$M + 1) + '-' + time2.$D + ' ' + time2.$H + ' : ' + time2.$m }).then((res) => {
      console.log(res.data);
      notification.success({ message: '修改行程信息成功' })
    })
    tripmanage_list().then((res) => {
      setList(res.data)
    })

  };
  // 对话框
  const [isModalOpen, setIsModalOpen] = useState(false);
  const handleOk = () => {
    // 使用submit调用onFinish函数
    form.submit()
    setIsModalOpen(false);
  

  };
  
  const handleCancel = () => {
    
    setIsModalOpen(false);

  };
  //删除
  var del = (record) => {
    del_list(record.id).then((res) => {
      console.log(res.data);
      notification.success({ message: '删除行程信息成功' })
    })
    tripmanage_list().then((res) => {
      setList(res.data)
    })
  }
  //搜索框
  const { Search } = Input;
  var [searchlist, setSearch] = useState([])
  const onSearch = (value) => {
    console.log(value);
    if (value) {
      search_list(value).then((res) => {
        if (res.data.length == 0) {
          notification.warning({ message: '查无此用户' })
        }
        setSearch(res.data)
        console.log(res.data);
      })
      tripmanage_list().then((res) => {
        setList(res.data)
      })
    } else {
      notification.warning({ message: '搜索内容为空' })
    }

  }
  const onSearch2 = (value) => {
    console.log(value)

    if (value) {
      search_list2(value).then((res) => {
        if (res.data.length == 0) {
          notification.warning({ message: '查无此用户' })
        }
        setSearch(res.data)
      })
      tripmanage_list().then((res) => {
        setList(res.data)
      })
    } else {
      notification.warning({ message: '搜索内容为空' })
    }
  }

  const [selectionType, setSelectionType] = useState('checkbox');
  var data = searchlist.length == 0 ? list : searchlist
  //复选框
  var [keys, setKeys] = useState([])
  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
      setKeys(selectedRowKeys)
    }
  };
  //keys链接数组

  //调用钩子函数
  var navigator = useNavigate()
  var add = () => {
    navigator('/index/tripadd')
  }
  //获取时间数据
  var [time, setTime] = useState([])
  var change = (value) => {
    console.log(value);
    setTime(value)
  }
  var [time2, setTime2] = useState({})
  var change2 = (value) => {
    console.log(value);
    setTime2(value)
  }
  //刷新页面
  var update = () => {
    navigator(0)
  }
  //分页
  var [pagination, setpaination] = useState({ current: 1, pageSize: 5, total: 20 })
  const handleChange = (pagination) => {
    console.log(pagination);
    setpaination(pagination)
    tripmanage_list().then((res) => {
      setList(res.data)
      setpaination({ current: pagination.current, pageSize: 5, total: res.data.length })
    })
  }
  //批量删除

  var moreDel = () => {
    axios.get(`/trip?_start=1&_end=${keys.length + 1}`).then((res) => {
      console.log(res.data);

    })

  }
  return (

    // 行程管理模块
    <div className='tripmanage'>
      <Breadcrumb>
        <Breadcrumb.Item>
          <a href='/index/home'>
            首页
          </a>
        </Breadcrumb.Item>
        <Breadcrumb.Item>
          <a href="">行程管理</a>
        </Breadcrumb.Item>
        <Breadcrumb.Item>
          <span>行程记录</span>
        </Breadcrumb.Item>
        <Button icon={<RedoOutlined />} className="update" type='primary' onClick={update} />
      </Breadcrumb>
      <div className="Card">
        <Card
          title="行程管理"
          bordered={false}
          className="Child"
          style={{
            width: 1250,

          }}
        >
          {/* 表格数据 */}
          <div>
            <Search
              placeholder="请输入学号"
              onSearch={onSearch}
              style={{
                width: 200,
              }}
              className="input1"
            />
            <Search
              placeholder="请输入学生姓名"
              allowClear
              onSearch={onSearch2}
              style={{
                width: 200,
              }}
              className="input2"
            />
            <Button type="primary" className='add' icon={<PlusCircleOutlined />} onClick={add}></Button>
            <div className='buttonBox'>

              {/* <Button type="primary" disabled={keys.length == 0} onClick={moreDel}>批量删除</Button> */}
              {/* <Button type="primary" disabled = {keys.length == 0}>批量修改行程</Button> */}
            </div>
            <Modal title="Basic Modal"  open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
              <Form
                labelCol={{ span: 6 }}
                wrapperCol={{ span: 18 }}
                onFinish={onFinish}
                // 绑定form实例
                form={form}


              >
                <Form.Item
                  label="学号"
                  name="con"
                  rules={[{ required: true, message: '输入学号' }]}
                  initialValue={params.con}
                >
                  <Input placeholder='输入账号' />
                </Form.Item>

                <Form.Item
                  label="姓名"
                  name="name"
                  rules={[{ required: true, message: '输入姓名' }]}
                  initialValue={params.name}
                >
                  <Input placeholder='输入姓名' />
                </Form.Item>

                <Form.Item
                  label="行程"
                  name="itinerary"
                  rules={[{ required: true, message: '输入行程' }]}
                  initialValue={params.itinerary}
                >
                  <Input placeholder='输入行程' />
                </Form.Item>

                <Form.Item name="date-picker" label="日期" {...config}>
                  <DatePicker onChange={change} format="YYYY-MM-DD" picker='date' />
                  {/* <DatePicker  onChange={change}/> */}
                </Form.Item>
                <Form.Item name="date-time-picker" label="添加时间" {...config}>
                  <DatePicker format="YYYY-MM-DD HH:mm:ss" onChange={change2} />
                </Form.Item>

                {/* <Form.Item
                      wrapperCol={{
                        ...layout.wrapperCol,
                        offset: 8,
                      }}
                    >
                      <Button type="primary" htmlType="submit">
                        Submit
                      </Button>
                    </Form.Item> */}
              </Form>
            </Modal>
            <Radio.Group
              onChange={({ target: { value } }) => {
                setSelectionType(value);
              }}
              value={selectionType}
            >
            </Radio.Group>

            <Table
              rowSelection={{
                type: selectionType,
                ...rowSelection,
              }}
              columns={columns}
              dataSource={data}
              pagination={pagination}
              onChange={handleChange}
            />
          </div>
        </Card>
      </div>
    </div>
  );
}

export default Tripmanage;